package com.sunfeng.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sunfeng.common.constant.ProductConstant;
import com.sunfeng.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.sunfeng.gulimall.product.dao.AttrGroupDao;
import com.sunfeng.gulimall.product.dao.CategoryDao;
import com.sunfeng.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.sunfeng.gulimall.product.entity.AttrGroupEntity;
import com.sunfeng.gulimall.product.entity.CategoryEntity;
import com.sunfeng.gulimall.product.service.AttrService;
import com.sunfeng.gulimall.product.service.CategoryService;
import com.sunfeng.gulimall.product.vo.AttrGroupRelationVO;
import com.sunfeng.gulimall.product.vo.AttrRespVO;
import com.sunfeng.gulimall.product.vo.AttrVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunfeng.common.utils.PageUtils;
import com.sunfeng.common.utils.Query;

import com.sunfeng.gulimall.product.dao.AttrDao;
import com.sunfeng.gulimall.product.entity.AttrEntity;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.xml.ws.Action;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAttr(AttrVO attrVO) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVO, attrEntity);
        // 保存基本数据
        this.save(attrEntity);
        // 规格参数才有分组  销售属性是没有分组的
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 保存关联关系
            AttrAttrgroupRelationEntity attrGroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrGroupRelationEntity.setAttrGroupId(attrVO.getAttrGroupId());
            // 获取attrId
            attrGroupRelationEntity.setAttrId(attrEntity.getAttrId());

            attrAttrgroupRelationDao.insert(attrGroupRelationEntity);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAttr(AttrVO attrVO) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVO, attrEntity);
        // 保存基本数据
        this.updateById(attrEntity);

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 保存关联关系
            AttrAttrgroupRelationEntity attrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrgroupRelationEntity.setAttrGroupId(attrVO.getAttrGroupId());
            // 获取attrId
            attrgroupRelationEntity.setAttrId(attrEntity.getAttrId());

            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVO.getAttrId()));
            // 如果有关联关系则是更新   如果不是则是插入
            if (count > 0) {
                attrAttrgroupRelationDao.update(attrgroupRelationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVO.getAttrId()));
            } else {
                attrAttrgroupRelationDao.insert(attrgroupRelationEntity);
            }
        }
    }

    /**
     * 查询基础属性
     *
     * @param params
     * @param catelogId
     * @param attrType
     * @return
     */
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {

        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(attrType) ?
                ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        //根据catelogId查询信息
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");

        if (StringUtils.isNoneEmpty(key)) {
            queryWrapper.and((wrapper -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            }));
        }
        // 负责查询
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVO> attrRespVOS = records.stream().map(attrEntity -> {
            AttrRespVO attrRespVO = new AttrRespVO();

            BeanUtils.copyProperties(attrEntity, attrRespVO);
            //设置分类和分组的名字
            if ("base".equalsIgnoreCase(attrType)) {
                // 设置分组名称  根据属性分组id  获取属性分组名称   一个属性只能属于一个分组
                AttrAttrgroupRelationEntity relationEntity =
                        attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));

                //设置分组的名称
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    attrRespVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            // 根据分类id 查询分类名称  这里可以做优化
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVO.setCatelogName(categoryEntity.getName());

            }
            return attrRespVO;
        }).collect(Collectors.toList());
        pageUtils.setList(attrRespVOS);
        return pageUtils;
    }

    /**
     * 获取分组的id
     *
     * @param attrId
     * @return
     */
    @Override
    public AttrRespVO getAttrInfo(Long attrId) {
        AttrRespVO attrRespVO = new AttrRespVO();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrRespVO);
        //判断是否是基本类型
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 设置分组id
            AttrAttrgroupRelationEntity attrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (null != attrgroupRelationEntity && attrgroupRelationEntity.getAttrGroupId() != null) {
                attrRespVO.setAttrGroupId(attrgroupRelationEntity.getAttrGroupId());
                // 设置分组名称
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelationEntity.getAttrGroupId());
                attrRespVO.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }
        /**
         * 设置分类信息
         */
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        // 设置分类路径
        attrRespVO.setCatelogPath(catelogPath);
        // 设置分类名称
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        attrRespVO.setCatelogName(categoryEntity.getName());


        return attrRespVO;
    }

    /**
     * 查询属性分组所有关联的属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {

        // 根据冗余表中的属性分组id 获取属性分组与属性关联关系列表
        List<AttrAttrgroupRelationEntity> attrAttrGroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        // 获取所有属性id
        List<Long> attrIds = attrAttrGroupRelationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        //如果attrIds为空就直接返回一个null值出去
        if (attrIds.size() == 0) {
            return null;
        }
        // 查询所有属性详细信息列表
        List<AttrEntity> attrEntityList = this.baseMapper.selectBatchIds(attrIds);

        return attrEntityList;
    }

    /**
     * 获取当前分组没有被关联的所有属性
     *
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {

        //1、当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        //获取当前分类的id
        Long catelogId = attrGroupEntity.getCatelogId();

        //2、当前分组只能关联别的分组没有引用的属性
        //2.1）、当前分类下的所有分组
        List<AttrGroupEntity> groupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));

        //获取当前分类的所有分组id
        List<Long> collect = groupEntities.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());


        //2.2）、这些分组关联的所有属性
        List<AttrAttrgroupRelationEntity> groupId = attrAttrgroupRelationDao.selectList
                (new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));

        // 获取所有分组关联的所有属性id
        List<Long> attrIds = groupId.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        //2.3）、从当前分类的所有属性移除这些属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        // 查询条件拼装  保证attrIds 有值的时候再进行拼装
        if (attrIds.size() > 0) {
            queryWrapper.notIn("attr_id", attrIds);
        }



        //判断是否有参数进行模糊查询
        String key = (String) params.get("key");
        if (!org.apache.commons.lang.StringUtils.isEmpty(key)) {
            queryWrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);


        return new PageUtils(page);
    }

    /**
     *  获取可搜索的属性值ids
     * @param attrIds
     * @return
     */
    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        List<Long> searchAttrIds = this.baseMapper.selectSearchAttrIds(attrIds);

        return searchAttrIds;
    }


}